package com.ruoyi.dynamic;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.query.entity.Query;
import com.ruoyi.sql.QueryUtil;
import com.ruoyi.util.ReflectUtil;

import java.time.LocalDate;
import java.util.Collection;

/**
 * **********************
 * * Author: XiaShiLong *
 * * Date  : 2021-03-30 *
 * * Time  : 11:34      *
 * * to    : lz&xm      *
 * **********************
 **/
public class DynamicQueryServiceImpl<M extends DynamicQueryMapper<T>, T> extends ServiceImpl<M, T> implements DynamicQueryService<T> {

    /**
     * 分页查询
     *
     * @param page  页码
     * @param size  每页数量
     * @param query 查询条件对象 <see>Query</see>
     * @return Page
     */
    @Override
    public Page<T> pageQuery(int page, int size, Query query) {
        return this.pageQuery(page, size, QueryUtil.getDynamicSqlForQuery(query));
    }

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 每页数量
     * @param sql  sql
     * @return Page
     */
    @Override
    public Page<T> pageQuery(int page, int size, String sql) {
        return this.getBaseMapper().executeSql(new Page<>(page, size), sql);
    }

    /**
     * 导出
     *
     * @param query 查询条件对象 <see>Query</see>
     * @return List
     */
    @Override
    public AjaxResult export(Query query) {
        Class<T> clz = ReflectUtil.getClass(query.getClassPath());
        ExcelUtil<T> excelUtil = new ExcelUtil<>(clz);
        return AjaxResult.success(
                excelUtil.exportExcel(
                        this.getBaseMapper().executeSql(QueryUtil.getDynamicSqlForQuery(query)),
                        LocalDate.now().toString()
                )
        );
    }

    @Override
    public boolean saveBatch(Collection<T> entityList, int batchSize) {
        entityList.forEach(e -> hitSuperEntity(e, true));
        return super.saveBatch(entityList, batchSize);
    }

    /**
     * 是否存在
     *
     * @param queryWrapper 查询条件对象
     * @return boolean true:存在, false:不存在
     */
    @Override
    public boolean exist(Wrapper<T> queryWrapper) {
        return super.count(queryWrapper) > 0;
    }

    /**
     * 保存并返回
     */
    @Override
    public T saveReturn(T entity) {
        this.save(entity);
        return entity;
    }

    @Override
    public boolean updateBatchById(Collection<T> entityList, int batchSize) {
        entityList.forEach(e -> hitSuperEntity(e, false));
        return super.updateBatchById(entityList, batchSize);
    }
}
